using AdminSG3L.Domain.Entities;
using AdminSG3L.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace AdminSG3L.Api;

/// <summary>
/// 数据库初始化服务 - 最终统合版本
/// </summary>
public class DatabaseInitializationService
{
    private readonly AdminDbContext _context;

    public DatabaseInitializationService(AdminDbContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 初始化数据库数据
    /// </summary>
    public async Task InitializeDatabaseAsync()
    {
        try
        {
            // 确保数据库已创建
            await _context.Database.EnsureCreatedAsync();
            Console.WriteLine("数据库已确保创建");

            // 检查数据库是否已有数据
            var hasUsers = await _context.Users.AnyAsync();
            var hasRoles = await _context.Roles.AnyAsync();
            var hasPermissions = await _context.Permissions.AnyAsync();
            var hasMenus = await _context.Menus.AnyAsync();

            // 检查用户角色关联是否存在
            var hasUserRoleAssociations = await _context.Users
                .Include(u => u.Roles)
                .AnyAsync(u => u.Roles.Any());

            // 检查角色权限关联是否存在
            var hasRolePermissionAssociations = await _context.Roles
                .Include(r => r.Permissions)
                .AnyAsync(r => r.Permissions.Any());

            // 检查角色菜单关联是否存在
            var hasRoleMenuAssociations = await _context.Roles
                .Include(r => r.Menus)
                .AnyAsync(r => r.Menus.Any());

            if (hasUsers && hasRoles && hasPermissions && hasMenus && 
                hasUserRoleAssociations && hasRolePermissionAssociations && hasRoleMenuAssociations)
            {
                Console.WriteLine("数据库已有完整数据，跳过初始化");
                Console.WriteLine($"当前数据统计 - 用户: {await _context.Users.CountAsync()}, " +
                                $"角色: {await _context.Roles.CountAsync()}, " +
                                $"权限: {await _context.Permissions.CountAsync()}, " +
                                $"菜单: {await _context.Menus.CountAsync()}");
                Console.WriteLine($"关联统计 - 用户角色: {hasUserRoleAssociations}, " +
                                $"角色权限: {hasRolePermissionAssociations}, " +
                                $"角色菜单: {hasRoleMenuAssociations}");
                return;
            }

            Console.WriteLine("数据库缺少完整数据或关联，开始初始化数据...");
            Console.WriteLine($"检查结果 - 用户: {hasUsers}, 角色: {hasRoles}, 权限: {hasPermissions}, 菜单: {hasMenus}");
            Console.WriteLine($"关联检查 - 用户角色: {hasUserRoleAssociations}, 角色权限: {hasRolePermissionAssociations}, 角色菜单: {hasRoleMenuAssociations}");

            // 强制清空并重新初始化数据（因为关联可能有问题）
            Console.WriteLine("强制清空数据库并重新初始化...");
            await ClearDatabaseAsync();

            // 创建角色
            Console.WriteLine("开始创建角色...");
            await CreateRolesAsync();

            // 创建权限
            Console.WriteLine("开始创建权限...");
            await CreatePermissionsAsync();

            // 创建菜单
            Console.WriteLine("开始创建菜单...");
            await CreateMenusAsync();

            // 创建用户
            Console.WriteLine("开始创建用户...");
            await CreateUsersAsync();

            // 分配角色权限和菜单
            Console.WriteLine("开始分配角色权限和菜单...");
            await AssignRolePermissionsAndMenusAsync();

            // 保存所有更改
            await _context.SaveChangesAsync();
            Console.WriteLine("数据库初始化完成！");
        }
        catch (Exception ex)
        {
            // 记录错误日志
            Console.WriteLine($"数据库初始化失败: {ex.Message}");
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
            throw;
        }
    }

    /// <summary>
    /// 强制重新初始化数据库（仅在需要时调用）
    /// </summary>
    public async Task ForceReinitializeDatabaseAsync()
    {
        try
        {
            // 确保数据库已创建
            await _context.Database.EnsureCreatedAsync();
            Console.WriteLine("数据库已确保创建");

            // 强制清空并重新初始化数据
            await ClearDatabaseAsync();

            // 创建角色
            Console.WriteLine("开始创建角色...");
            await CreateRolesAsync();

            // 创建权限
            Console.WriteLine("开始创建权限...");
            await CreatePermissionsAsync();

            // 创建菜单
            Console.WriteLine("开始创建菜单...");
            await CreateMenusAsync();

            // 创建用户
            Console.WriteLine("开始创建用户...");
            await CreateUsersAsync();

            // 分配角色权限和菜单
            Console.WriteLine("开始分配角色权限和菜单...");
            await AssignRolePermissionsAndMenusAsync();

            // 保存所有更改
            await _context.SaveChangesAsync();
            Console.WriteLine("数据库强制重新初始化完成！");
        }
        catch (Exception ex)
        {
            // 记录错误日志
            Console.WriteLine($"数据库强制重新初始化失败: {ex.Message}");
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
            throw;
        }
    }

    /// <summary>
    /// 清空数据库所有数据
    /// </summary>
    private async Task ClearDatabaseAsync()
    {
        // 清空所有表数据 - 注意外键约束，需要按正确顺序删除
        _context.Users.RemoveRange(_context.Users);
        _context.Roles.RemoveRange(_context.Roles);
        _context.Permissions.RemoveRange(_context.Permissions);
        _context.Menus.RemoveRange(_context.Menus);
        
        await _context.SaveChangesAsync();
        Console.WriteLine("数据库已清空");
    }

    private async Task CreateRolesAsync()
    {
        // 系统角色 - 不可删除修改
        var superAdminRole = AppRole.Create("超级管理员", "super_admin", "系统超级管理员，拥有所有权限", true);
        var systemAdminRole = AppRole.Create("系统管理员", "system_admin", "系统管理员，拥有部分管理权限", true);
        var dataAnalystRole = AppRole.Create("数据分析师", "data_analyst", "数据分析师，专注数据分析相关功能", true);
        var devOpsRole = AppRole.Create("运维人员", "devops", "运维人员，负责系统监控和维护", true);
        var developerRole = AppRole.Create("开发者", "developer", "开发者，负责模板和组件开发", true);
        var regularUserRole = AppRole.Create("普通用户", "regular_user", "普通用户，拥有基础功能权限", true);

        await _context.Roles.AddRangeAsync(
            superAdminRole, systemAdminRole, dataAnalystRole, 
            devOpsRole, developerRole, regularUserRole
        );
    }

    private async Task CreatePermissionsAsync()
    {
        var permissions = new List<AppPermission>();

        // 仪表盘权限
        permissions.Add(AppPermission.Create("仪表盘查看", "dashboard.view", "查看仪表盘页面"));
        permissions.Add(AppPermission.Create("实时数据仪表盘", "dashboard.realtime", "查看实时数据仪表盘"));

        // 用户管理权限
        permissions.Add(AppPermission.Create("查看用户列表", "user.view", "查看用户列表"));
        permissions.Add(AppPermission.Create("创建新用户", "user.create", "创建新用户"));
        permissions.Add(AppPermission.Create("编辑用户信息", "user.update", "编辑用户信息"));
        permissions.Add(AppPermission.Create("删除用户", "user.delete", "删除用户"));
        permissions.Add(AppPermission.Create("分配用户角色", "user.assign", "分配用户角色"));
        permissions.Add(AppPermission.Create("重置密码", "user.resetPassword", "重置用户密码"));
        permissions.Add(AppPermission.Create("用户搜索", "user.search", "搜索用户"));

        // 角色管理权限
        permissions.Add(AppPermission.Create("查看角色列表", "role.view", "查看角色列表"));
        permissions.Add(AppPermission.Create("创建新角色", "role.create", "创建新角色"));
        permissions.Add(AppPermission.Create("编辑角色信息", "role.update", "编辑角色信息"));
        permissions.Add(AppPermission.Create("删除角色", "role.delete", "删除角色"));
        permissions.Add(AppPermission.Create("分配角色权限", "role.assign", "分配角色权限"));
        permissions.Add(AppPermission.Create("配置角色菜单", "role.menu", "配置角色菜单"));
        permissions.Add(AppPermission.Create("启用禁用角色", "role.status", "启用或禁用角色"));

        // 权限管理权限
        permissions.Add(AppPermission.Create("查看权限列表", "permission.view", "查看权限列表"));
        permissions.Add(AppPermission.Create("创建新权限", "permission.create", "创建新权限"));
        permissions.Add(AppPermission.Create("编辑权限信息", "permission.update", "编辑权限信息"));
        permissions.Add(AppPermission.Create("删除权限", "permission.delete", "删除权限"));
        permissions.Add(AppPermission.Create("权限树管理", "permission.tree", "管理权限树结构"));
        permissions.Add(AppPermission.Create("启用禁用权限", "permission.status", "启用或禁用权限"));

        // 菜单管理权限
        permissions.Add(AppPermission.Create("查看菜单列表", "menu.view", "查看菜单列表"));
        permissions.Add(AppPermission.Create("创建新菜单", "menu.create", "创建新菜单"));
        permissions.Add(AppPermission.Create("编辑菜单信息", "menu.update", "编辑菜单信息"));
        permissions.Add(AppPermission.Create("删除菜单", "menu.delete", "删除菜单"));
        permissions.Add(AppPermission.Create("菜单排序", "menu.sort", "菜单排序"));
        permissions.Add(AppPermission.Create("菜单分配到角色", "menu.assign", "将菜单分配到角色"));

        // 数据分析权限
        permissions.Add(AppPermission.Create("数据分析仪表盘", "analytics.dashboard", "查看数据分析仪表盘"));
        permissions.Add(AppPermission.Create("图表查看", "analytics.chart", "查看各类图表"));
        permissions.Add(AppPermission.Create("实时数据分析", "analytics.realtime", "查看实时数据分析"));

        // 日志管理权限
        permissions.Add(AppPermission.Create("查看系统日志", "log.view", "查看系统日志"));
        permissions.Add(AppPermission.Create("清空日志", "log.delete", "清空系统日志"));
        permissions.Add(AppPermission.Create("日志搜索筛选", "log.search", "搜索和筛选日志"));

        // 监控管理权限
        permissions.Add(AppPermission.Create("系统监控", "monitoring.system", "查看系统监控信息"));
        permissions.Add(AppPermission.Create("性能监控", "monitoring.performance", "查看性能监控"));
        permissions.Add(AppPermission.Create("告警管理", "monitoring.alerts", "管理系统告警"));

        // 模板组件权限
        permissions.Add(AppPermission.Create("查看模板中心", "template.view", "查看模板中心"));
        permissions.Add(AppPermission.Create("创建新模板", "template.create", "创建新模板"));
        permissions.Add(AppPermission.Create("编辑模板", "template.edit", "编辑模板"));
        permissions.Add(AppPermission.Create("删除模板", "template.delete", "删除模板"));
        permissions.Add(AppPermission.Create("查看组件中心", "component.view", "查看组件中心"));
        permissions.Add(AppPermission.Create("组件管理", "component.manage", "管理组件"));

        // 个人中心权限
        permissions.Add(AppPermission.Create("个人资料查看", "profile.view", "查看个人资料"));
        permissions.Add(AppPermission.Create("更新个人信息", "profile.update", "更新个人信息"));

        // 系统设置权限
        permissions.Add(AppPermission.Create("系统设置", "system.settings", "系统设置管理"));

        await _context.Permissions.AddRangeAsync(permissions);
    }

    private async Task CreateMenusAsync()
    {
        var menus = new List<AppMenu>();

        // 工作台分组 - 一级菜单
        var dashboardMenu = AppMenu.Create("仪表盘", "dashboard", null, null, null, "Dashboard", "/home", "系统仪表盘", true);
        var analyticsMenu = AppMenu.Create("分析页", "analytics", null, null, null, "TrendCharts", "/home/analytics", "数据分析页面", true);
        var monitoringMenu = AppMenu.Create("监控页", "monitoring", null, null, null, "Monitor", "/home/monitoring", "系统监控页面", true);
        
        // 开发工具分组 - 模板中心（有子菜单）
        var templateCenterMenu = AppMenu.Create("模板中心", "template-center", null, null, null, "Grid", "/home/template-center", "模板中心", true);
        
        // 开发工具分组 - 组件中心（有子菜单）
        var componentCenterMenu = AppMenu.Create("组件中心", "component-center", null, null, null, "Histogram", "/home/component-center", "组件中心", true);
        
        // 系统管理分组 - 一级菜单
        var userManagementMenu = AppMenu.Create("用户管理", "users", null, null, null, "User", "/home/users", "用户管理页面", true);
        var roleManagementMenu = AppMenu.Create("角色管理", "roles", null, null, null, "UserFilled", "/home/roles", "角色管理页面", true);
        var permissionManagementMenu = AppMenu.Create("权限管理", "permissions", null, null, null, "Key", "/home/permissions", "权限管理页面", true);
        var systemSettingsMenu = AppMenu.Create("系统设置", "settings", null, null, null, "Setting", "/home/settings", "系统设置页面", true);
        
        // 日志中心菜单
        var logCenterMenu = AppMenu.Create("日志中心", "logs", null, null, null, "Document", "/home/logs", "系统日志管理", true);
        
        // 个人中心菜单（不在菜单栏显示，hideInMenu: true）

        // 先添加一级菜单
        menus.AddRange(new[]
        {
            dashboardMenu, analyticsMenu, monitoringMenu, templateCenterMenu, componentCenterMenu,
            userManagementMenu, roleManagementMenu, permissionManagementMenu,
            systemSettingsMenu, logCenterMenu
        });

        await _context.Menus.AddRangeAsync(menus);
        await _context.SaveChangesAsync(); // 保存一级菜单

        // 然后添加模板中心的子菜单
        var templateListMenu = AppMenu.Create("模板案例", "templates", templateCenterMenu.Id, null, null, "Collection", "/home/template-center/templates", "模板案例页面", true);
        var createTemplateMenu = AppMenu.Create("创建模板", "create-template", templateCenterMenu.Id, null, null, "Plus", "/home/template-center/create", "创建模板页面", true);
        
        // 添加组件中心的子菜单
        var basicComponentsMenu = AppMenu.Create("基本组件", "basic-components", componentCenterMenu.Id, null, null, "Grid", "/home/component-center/basic", "基本组件页面", true);
        var iconComponentsMenu = AppMenu.Create("图标组件", "icon-components", componentCenterMenu.Id, null, null, "Star", "/home/component-center/icons", "图标组件页面", true);
        var chartComponentsMenu = AppMenu.Create("图形组件", "chart-components", componentCenterMenu.Id, null, null, "TrendCharts", "/home/component-center/charts", "图形组件页面", true);

        await _context.Menus.AddRangeAsync(new[]
        {
            templateListMenu, createTemplateMenu, basicComponentsMenu, iconComponentsMenu, chartComponentsMenu
        });
    }

    private async Task CreateUsersAsync()
    {
        var superAdminUser = AppUser.Create("超级管理员", "superadmin", "Admin@123456", "superadmin@system.com", "", "系统超级管理员账户", true);
        var systemAdminUser = AppUser.Create("系统管理员", "sysadmin", "Admin@123456", "sysadmin@system.com", "", "系统管理员账户", true);
        var normalUser = AppUser.Create("普通用户", "user", "User@123456", "user@example.com", "", "普通用户账户", false);

        await _context.Users.AddRangeAsync(superAdminUser, systemAdminUser, normalUser);
    }

    private async Task AssignRolePermissionsAndMenusAsync()
    {
        // 等待所有数据保存后再分配关系
        await _context.SaveChangesAsync();

        // 获取所有角色、权限和菜单
        var roles = await _context.Roles.ToListAsync();
        var permissions = await _context.Permissions.ToListAsync();
        var menus = await _context.Menus.ToListAsync();
        var users = await _context.Users.ToListAsync();

        Console.WriteLine($"开始分配关系 - 角色数量: {roles.Count}, 权限数量: {permissions.Count}, 菜单数量: {menus.Count}, 用户数量: {users.Count}");

        // 如果用户数量为0，说明用户创建有问题，重新尝试创建用户
        if (users.Count == 0)
        {
            Console.WriteLine("检测到用户数量为0，重新创建用户...");
            await CreateUsersAsync();
            await _context.SaveChangesAsync();
            users = await _context.Users.ToListAsync();
            Console.WriteLine($"重新创建后用户数量: {users.Count}");
        }

        // 根据角色代码分配权限和菜单
        foreach (var role in roles)
        {
            var rolePermissions = GetPermissionsForRole(role.RoleCode, permissions);
            var roleMenus = GetMenusForRole(role.RoleCode, menus);

            Console.WriteLine($"角色 {role.RoleName} ({role.RoleCode}) - 权限: {rolePermissions.Count}, 菜单: {roleMenus.Count}");

            foreach (var permission in rolePermissions)
            {
                role.AddPermission(permission);
            }

            foreach (var menu in roleMenus)
            {
                role.AddMenu(menu);
            }
        }

        // 保存角色权限和菜单关联
        await _context.SaveChangesAsync();
        Console.WriteLine("角色权限和菜单关联已保存");

        // 为用户分配角色
        var superAdminRole = roles.FirstOrDefault(r => r.RoleCode == "super_admin");
        var systemAdminRole = roles.FirstOrDefault(r => r.RoleCode == "system_admin");
        var regularUserRole = roles.FirstOrDefault(r => r.RoleCode == "regular_user");

        var superAdminUser = users.FirstOrDefault(u => u.Username == "superadmin");
        var systemAdminUser = users.FirstOrDefault(u => u.Username == "sysadmin");
        var normalUser = users.FirstOrDefault(u => u.Username == "user");

        // 分配用户角色
        if (superAdminUser != null && superAdminRole != null)
        {
            superAdminUser.AddRole(superAdminRole);
            Console.WriteLine($"用户 {superAdminUser.Username} 分配角色 {superAdminRole.RoleName}");
        }

        if (systemAdminUser != null && systemAdminRole != null)
        {
            systemAdminUser.AddRole(systemAdminRole);
            Console.WriteLine($"用户 {systemAdminUser.Username} 分配角色 {systemAdminRole.RoleName}");
        }

        if (normalUser != null && regularUserRole != null)
        {
            normalUser.AddRole(regularUserRole);
            Console.WriteLine($"用户 {normalUser.Username} 分配角色 {regularUserRole.RoleName}");
        }

        // 保存用户角色关联
        await _context.SaveChangesAsync();
        Console.WriteLine("用户角色关联已保存");
    }

    private List<AppPermission> GetPermissionsForRole(string? roleCode, List<AppPermission> allPermissions)
    {
        var permissionCodes = roleCode switch
        {
            "super_admin" => new[]
            {
                "dashboard.view", "dashboard.realtime",
                "user.view", "user.create", "user.update", "user.delete", "user.assign", "user.resetPassword", "user.search",
                "role.view", "role.create", "role.update", "role.delete", "role.assign", "role.menu", "role.status",
                "permission.view", "permission.create", "permission.update", "permission.delete", "permission.tree", "permission.status",
                "menu.view", "menu.create", "menu.update", "menu.delete", "menu.sort", "menu.assign",
                "analytics.dashboard", "analytics.chart", "analytics.realtime",
                "log.view", "log.delete", "log.search",
                "monitoring.system", "monitoring.performance", "monitoring.alerts",
                "template.view", "template.create", "template.edit", "template.delete",
                "component.view", "component.manage",
                "profile.view", "profile.update",
                "system.settings"
            },
            "system_admin" => new[]
            {
                "dashboard.view",
                "user.view", "user.create", "user.update", "user.assign", "user.search",
                "role.view", "role.assign",
                "permission.view",
                "menu.view",
                "analytics.dashboard", "analytics.chart",
                "log.view",
                "monitoring.system",
                "template.view",
                "component.view",
                "profile.view", "profile.update",
                "system.settings"
            },
            "data_analyst" => new[]
            {
                "dashboard.view", "dashboard.realtime",
                "analytics.dashboard", "analytics.chart", "analytics.realtime",
                "user.view",
                "role.view",
                "log.view",
                "monitoring.system",
                "profile.view", "profile.update"
            },
            "devops" => new[]
            {
                "dashboard.view",
                "monitoring.system", "monitoring.performance", "monitoring.alerts",
                "log.view", "log.search",
                "analytics.dashboard",
                "profile.view", "profile.update",
                "system.settings"
            },
            "developer" => new[]
            {
                "dashboard.view",
                "template.view", "template.create", "template.edit",
                "component.view", "component.manage",
                "user.view",
                "role.view",
                "analytics.chart",
                "profile.view", "profile.update"
            },
            "regular_user" => new[]
            {
                "dashboard.view",
                "template.view",
                "component.view",
                "analytics.chart",
                "profile.view", "profile.update","system.settings"
            },
            _ => Array.Empty<string>()
        };

        return allPermissions.Where(p => permissionCodes.Contains(p.PermissionCode)).ToList();
    }

    private List<AppMenu> GetMenusForRole(string? roleCode, List<AppMenu> allMenus)
    {
        var menuCodes = roleCode switch
        {
            "super_admin" => new[]
            {
                "dashboard", "analytics", "monitoring", "template-center", "templates", "create-template",
                "component-center", "basic-components", "icon-components", "chart-components",
                "users", "roles", "permissions", "settings", "logs"
            },
            "system_admin" => new[]
            {
                "dashboard", "analytics", "template-center", "templates", "create-template",
                "component-center", "basic-components", "icon-components", "chart-components",
                "users", "roles", "permissions", "logs", "settings"
            },
            "data_analyst" => new[]
            {
                "dashboard", "analytics", "monitoring"
            },
            "devops" => new[]
            {
                "dashboard", "monitoring", "logs", "analytics", "settings"
            },
            "developer" => new[]
            {
                "dashboard", "template-center", "templates", "create-template",
                "component-center", "basic-components", "icon-components", "chart-components", "analytics"
            },
            "regular_user" => new[]
            {
                "dashboard", "template-center", "templates",
                "component-center", "basic-components", "icon-components", "chart-components","settings"
            },
            _ => Array.Empty<string>()
        };

        return allMenus.Where(m => menuCodes.Contains(m.MenuCode)).ToList();
    }
}
